// pages/Personal_matches/index.js
const app = getApp();
import {
  deleteMatch,
  enableMatch,
  updatematchinfo
} from '../../../http/game'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    staticUrl: app.globalData.staticUrl,
    sponsorlogoes: [],
    logoUrl: [],
    latitude: "",
    longitude: "",
    page: 1,
    type_id: "all",
    ordertype: 1,
    personal_matches: [],
    flag: true,
    isbottom: false,
    search: "",
    userInfo: app.globalData.userInfo,
    watch_typelists: [{
        name: '私密',
        value: '0'
      },
      {
        name: '公开',
        value: '1',
        checked: 'true'
      },
      {
        name: '好友公开',
        value: '2'
      },
    ],
        // 设置开始的位置
        startX: 0,
        startY: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      sponsorlogoes: app.globalData.sponsorlogoes,
      logoUrl: app.globalData.imagelogourl,
    });
    var userInfo = app.globalData.userInfo;
    this.setData({
      userInfo
    });
    this.getpersonalmatcheslists();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.popupCalendar = this.selectComponent("#popupCalendar");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (course) {
    var userInfo = app.globalData.userInfo;
    this.setData({
      userInfo
    });
    var location = wx.getStorageSync('location');
    if (location && location.lng && location.lat) {
      this.setData({
        latitude: location.lng,
        longitude: location.lat
      })
    } else {
      var that = this;
      /*wx.getLocation({
        type: 'wgs84',
        success: (result) => {
          const latitude = result.latitude
          const longitude = result.longitude
          const speed = result.speed
          const accuracy = result.accuracy
          that.setData({
            longitude: longitude,
            latitude: latitude
          });
          wx.setStorageSync('location', {
            lng: longitude,
            lat: latitude
          });

        },
        fail: (res) => {},
        complete: (res) => {},
      })*/
    }
    if (!!course) {
      this.setData({
        'selectmatchdata.pm_cr_hole': course.cr_hole,
        'selectmatchdata.pm_cr_id': course.course_id,
        'selectmatchdata.cr_cn_name': course.course_name,
      })
    } else return
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getpersonalmatcheslists();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  inputSearch: function (e) {
    this.setData({
      search: e.detail.value
    });
  },

  changeRules: function (e) {
    this.setData({
      ordertype: e.currentTarget.dataset.index,
      personal_matches: [],
      isbottom: false,
      page: 1
    });
    this.getpersonalmatcheslists();
  },

  searchF: function () {
    this.setData({
      personal_matches: [],
      isbottom: false
    });
    this.getpersonalmatcheslists();
  },

  // 开始滑动
  touchStart(e) {
    console.log('touchStart=====>', e);
    let personal_matches = [...this.data.personal_matches]
    personal_matches.forEach(item => {
      if (item.isTouchMove) {
        item.isTouchMove = !item.isTouchMove;
      }
    });
    this.setData({
      personal_matches: personal_matches,
      startX: e.touches[0].clientX,
      startY: e.touches[0].clientY
    })
  },

  touchMove(e) {
    console.log('touchMove=====>', e);
    let moveX = e.changedTouches[0].clientX;
    let moveY = e.changedTouches[0].clientY;
    let indexs = e.currentTarget.dataset.index;
    let personal_matches = [...this.data.personal_matches]

    let angle = this.angle({
      X: this.data.startX,
      Y: this.data.startY
    }, {
      X: moveX,
      Y: moveY
    });

    personal_matches.forEach((item, index) => {
      item.isTouchMove = false;
      // 如果滑动的角度大于30° 则直接return；
      if (angle > 30) {
        return
      }

      if (indexs === index) {
        if (moveX > this.data.startX) { // 右滑
          item.isTouchMove = false;
        } else { // 左滑
          item.isTouchMove = true;
        }
      }
    })

    this.setData({
      personal_matches
    })
    console.log(personal_matches);
  },

  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  getpersonalmatcheslists: function () {
    var params = {};
    let {
      type_id,
      search,
      page,
      ordertype,
      latitude,
      longitude,
      personal_matches,
      isbottom,
      userInfo
    } = this.data;
    params.type_id = type_id;
    params.search = search;
    params.page = page;
    params.order = ordertype;
    params.latitude = latitude;
    params.longitude = longitude;
    params.player_id = userInfo.player_id;
    params.pl_id = userInfo.player_id;
    wx.showNavigationBarLoading();
    var that = this;
    console.log(params);
    app.getpersonalmatcheslists(params, function (res) {
        console.log(res);
        if (res.data.data && res.data.data.length > 0) {
          if (personal_matches.length > 0) {
            personal_matches = personal_matches.concat(res.data.data);

          } else {
            personal_matches = res.data.data;
          }
          page++;
        } else {
          if (personal_matches.length > 0) {
            isbottom = true;
          }
        }
        that.setData({
          personal_matches,
          page,
          isbottom
        });
      },
      function () {
        wx.hideNavigationBarLoading();
      })
  },

  _openpersonalmatch: function (e) {

    var matchplay = e.currentTarget.dataset.personalmatches;
    wx.navigateTo({
      url: '../match/match?match_id=' + matchplay.match_id,
    })

  },

  deletematches: function (e) {
    const {
      personalmatches,
      index
    } = e.currentTarget.dataset;

    let {
      personal_matches,
      userInfo
    } = this.data;
    console.log(userInfo);
    var that = this;
    if (personalmatches) {
      wx.showModal({
        title: '删除记分卡提示',
        content: '是否删除此记分卡？\r\n删除之后将不能恢复',
        confirmText: '确定',
        cancelText: '再看看',
        success: function (res) {
          if (res.confirm) {
            wx.showModal({
              title: '确认删除记分卡提示',
              content: '确认删除？\r\n删除之后成绩将不能恢复',
              confirmText: '确定',
              cancelText: '再看看',
              success: function (res) {
                if (res.confirm) {
                  console.log(userInfo.player_id);
                  deleteMatch({
                    match_id: personalmatches.match_id,
                    player_id: userInfo.player_id
                  }).then(res => {
                    if (res.errorcode.code == 'ok') {
                      wx.showToast({
                        title: '删除成功',
                        duration: 2000,
                        icon: 'success'
                      })
                      personal_matches.splice(index, 1);
                      that.setData({
                        personal_matches
                      });
                    }
                  })
                }
              }
            })
          }
        }
      })
    }
  },

  showupdatematches: function (e) {
    const {
      personalmatches,
      index
    } = e.currentTarget.dataset;

    let {
      personal_matches,
      userInfo
    } = this.data;
    console.log(userInfo);
    var that = this;
    if (personalmatches) {
      this.setData({
        flag: false,
        selectmatchdata: personalmatches
      });
    }
  },

  controlShowFloat(e) {
    let {
      show
    } = e.currentTarget.dataset
    if (show) return
    else {
      this.hidePopup()
    }
  },
  //隐藏弹框
  hidePopup: function () {
    this.setData({
      flag: !this.data.flag
    })
  },
  //展示弹框
  showPopup() {
    this.setData({
      flag: !this.data.flag
    })
  },

  opencal: function () {
    if (this.data.selectmatchdata.pm_status == 1) {
      this.popupCalendar.showPopup();
    } else {
      wx.showToast({
        title: '记分卡' + (this.data.selectmatchdata.pm_status == 2 ? '进行中' : '已结束') + '不能修改时间',
        duration: 3000,
        icon: 'none'
      })
    }
  },

  // 选择观战方式
  radioChangeWatch(data) {
    this.setData({
      'selectmatchdata.pm_watch': data.detail.value
    })
    console.log(this.data.selectmatchdata);
  },


  // 跳转到选择城市
  area_selcet() {
    if (this.data.selectmatchdata.pm_status == 1) {
      wx.navigateTo({
        url: '/pages/Personal_matches/area/area'
      });
    } else {
      wx.showToast({
        title: '记分卡' + (this.data.selectmatchdata.pm_status == 2 ? '进行中' : '已结束') + '不能修改球场',
        duration: 3000,
        icon: 'none'
      })
    }
  },

  //组件监听事件
  select(e) {
    this.setData({
      //match_date: e.detail,
      'selectmatchdata.pm_start_date': e.detail
    })
  },

  _errorcal() {
    this.popupCalendar.hidePopup();
  },

  async getCourseList() {
    let course = null
    const {
      course_id
    } = this.data.creatmatchdata
    const location = wx.getStorageSync('location')
    const {
      data
    } = await getCourseList(location)
    if (course_id) {
      course = data.list.filter(item => item.course_id == course_id)[0] || null
    } else {
      course = data.near.length > 0 ? data.near[0] : null
    }
    this.setData({
      course_name: course.course_name || '请选择球场',
      'creatmatchdata.course_id': course.course_id || '',
      course
    })
  },

  enablematches: function (e) {
    const {
      personalmatches,
      index
    } = e.currentTarget.dataset;

    let {
      personal_matches,
      userInfo
    } = this.data;
    console.log(userInfo);
    var that = this;
    if (personalmatches) {
      var text = "启用";
      if (personalmatches.pm_act == '1') {
        text = '禁用';
      }
      wx.showModal({
        title: text + '记分卡提示',
        content: '是否' + text + '此记分卡？',
        confirmText: '确定',
        cancelText: '再看看',
        success: function (res) {
          if (res.confirm) {
            console.log(userInfo.player_id);
            enableMatch({
              match_id: personalmatches.match_id,
              player_id: userInfo.player_id,
              act: personalmatches.pm_act
            }).then(res => {
              if (res.errorcode.code == 'ok') {
                wx.showToast({
                  title: text + '成功',
                  duration: 2000,
                  icon: 'success'
                })
                personal_matches[index].pm_act = personalmatches.pm_act == 1 ? 0 : 1;
                that.setData({
                  personal_matches
                });
                console.log(personal_matches);
              }

            })
          }
        }
      })
    }
  },

  inputvalue: function (e) {
    this.setData({
      'selectmatchdata.pm_cn_name': e.detail.value
    })
  },

  updatematchplay: function () {


    const {
      selectmatchdata,
      userInfo,
      personal_matches
    } = this.data

    var that = this;
    console.log(selectmatchdata);
    if (!selectmatchdata.pm_cn_name) {
      wx.showToast({
        title: '记分卡名字不能为空',
        icon: 'none',
      })
      return;
    }
    if (!selectmatchdata.pm_cr_id) {
      wx.showToast({
        title: '球场不能为空',
        icon: 'none',
      })
      return;
    }
    // 修改比赛接口
    updatematchinfo({
      pm_cn_name: selectmatchdata.pm_cn_name,
      pm_cr_id: selectmatchdata.pm_cr_id,
      pm_cr_hole: selectmatchdata.pm_cr_hole,
      pm_start_date: selectmatchdata.pm_start_date,
      pm_watch: selectmatchdata.pm_watch,
      match_id: selectmatchdata.match_id,
      player_id: userInfo.player_id,
    }).then(async (res) => {

      wx.showToast({
        title: '修改赛事信息成功',
        icon: 'none',
        complete: () => {
          that.hidePopup();
          var index = 0;
          personal_matches.forEach(item => {

            if (item.match_id == selectmatchdata.match_id) {
              personal_matches[index] = selectmatchdata;
              console.log(personal_matches[index]);
            }
            index++;
          })
          console.log(personal_matches);
          that.setData({
            personal_matches
          });
        }
      })
    })
  },

  creatematches: function () {
    var userInfo = app.globalData.userInfo;
    console.log(userInfo);
    var title = "";
    var page = "";
    if (!userInfo || !userInfo.openid) {
      title = "请先登录之后后才能创建球局";
      page = "/pages/login/login";
    }

    if (userInfo && userInfo.openid && (!userInfo.trueName || !userInfo.player_id)) {
      title = "注册球员信息才能创建球局";
      page = "/pages/More/information/information";
    }

    if (title) {
      wx.showModal({
        title: title,
        cancelText: '再看看',
        confirmText: 'OK',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: page,
            })
          } else if (res.cancel) {

          }
        }
      })
    } else {
      wx.navigateTo({
        url: '../Personal_matches/createpersonalmatch/create',
      })
    }
  }

})